<?php

/**
 * Class UserActivation_Model
 */
class Captcha_Model extends CI_Model
{
    /**
     *
     */
    public function __construct()
    {
        parent::__construct();
    }

    public static function isWordExistAndDeleteItSelfByWord($word)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        //先GC，清掉过期的激活码
        self::GC();

        $CI->db->select('captcha.*');
        $CI->db->from('captcha');
        $CI->db->where('captcha.word', $word);

        $query = $CI->db->get();
        $row   = $query->row();

        if ($row) {
            self::deleteById($row->id);
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param array $captcha
     * @throws ParaException
     * @return object
     */
    public static function update($captcha)
    {
        if (!$captcha || !$captcha['time'] || !$captcha['word']) {
            throw new ParaException('参数不正确');
        }

        /** @var CI $CI */
        $CI =& get_instance();

        $result = $CI->db->insert('captcha',
            array(
                'time' => $captcha['time'] + 7200,
                'ip'   => $CI->input->ip_address(),
                'word' => $captcha['word'],
            )
        );

        self::GC();

        return $result;
    }

    /**
     * @param int $id
     * @return bool
     */
    public static function deleteById($id)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        self::GC();

        $CI->db->where('captcha.id', $id);
        $result = $CI->db->delete('captcha');

        if ($result)
            return true;
        else
            return false;
    }

    public static function isWordExist($word)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        self::GC();

        $CI->db->select('captcha.*');
        $CI->db->from('captcha');
        $CI->db->where('captcha.word', $word);
        if ($CI->db->get()->num_rows())
            return true;
        else
            return false;
    }

    public static function GC()
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->where('captcha.time <', time());
        $CI->db->delete('captcha');
    }

}
